package com.example.exceldemo.service.impl;

import com.example.exceldemo.service.ApiService;
import com.example.exceldemo.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;

/**
 * API服务实现类
 */
@Slf4j
@Service
public class ApiServiceImpl implements ApiService {

    /**
     * API配置常量
     */
    private static final String API_URL = "http://192.168.175.101/v1/workflows/run";
    private static final String API_TOKEN = "Bearer app-snZmsJCXWoIU8n2HsRDfY4Z8";
    
    /**
     * 任务服务
     */
    private final TaskService taskService;
    
    /**
     * 构造方法注入
     */
    @Autowired
    public ApiServiceImpl(TaskService taskService) {
        this.taskService = taskService;
    }

    @Override
    public String callApi(JSONObject requestBody) throws Exception {
        log.info("发送同步API请求: {}", API_URL);
        
        URL url = new URL(API_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", API_TOKEN);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        connection.setConnectTimeout(10000); // 10秒连接超时
        connection.setReadTimeout(60000);    // 60秒读取超时
        
        // 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.toString().getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
        
        // 获取响应
        int statusCode = connection.getResponseCode();
        if (statusCode != 200) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                StringBuilder errorResponse = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    errorResponse.append(responseLine.trim());
                }
                throw new RuntimeException("API请求失败，状态码: " + statusCode + ", 响应: " + errorResponse);
            }
        }
        
        // 读取响应内容
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            return response.toString();
        }
    }

    @Override
    public String callApiAsync(JSONObject requestBody, String metadata) {
        log.info("发送异步API请求: {}", API_URL);
        
        // 创建任务
        String taskType = "API_CALL";
        final String taskId = taskService.createTask(taskType, metadata).getTaskId();
        
        // 异步执行API调用
        CompletableFuture.runAsync(() -> {
            try {
                // 更新进度为10%（开始处理）
                taskService.updateTaskProgress(taskId, 10);
                
                // 创建连接
                URL url = new URL(API_URL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Authorization", API_TOKEN);
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setDoOutput(true);
                connection.setConnectTimeout(10000); // 10秒连接超时
                connection.setReadTimeout(300000);   // 5分钟读取超时
                
                // 更新进度为30%（连接已建立）
                taskService.updateTaskProgress(taskId, 30);
                
                // 发送请求
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = requestBody.toString().getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }
                
                // 更新进度为50%（请求已发送）
                taskService.updateTaskProgress(taskId, 50);
                
                // 获取响应
                int statusCode = connection.getResponseCode();
                if (statusCode != 200) {
                    try (BufferedReader br = new BufferedReader(
                            new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                        StringBuilder errorResponse = new StringBuilder();
                        String responseLine;
                        while ((responseLine = br.readLine()) != null) {
                            errorResponse.append(responseLine.trim());
                        }
                        throw new RuntimeException("API请求失败，状态码: " + statusCode + ", 响应: " + errorResponse);
                    }
                }
                
                // 更新进度为80%（正在读取响应）
                taskService.updateTaskProgress(taskId, 80);
                
                // 读取响应内容
                StringBuilder response = new StringBuilder();
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                }
                
                // 更新进度为100%（处理完成）
                taskService.completeTask(taskId, response.toString());
                log.info("异步API请求完成: {}", taskId);
                
            } catch (Exception e) {
                log.error("异步API请求失败: {}", e.getMessage(), e);
                taskService.failTask(taskId, e.getMessage());
            }
        });
        
        return taskId;
    }
} 